﻿using System;
using System.Collections.Generic;
using System.Text.RegularExpressions;
using System.Xml.Linq;
using System.Linq;
using System.Threading;
using MediaPortal.GUI.Library;

namespace MyNetflix2
{
    public class ODataItem
    {
        #region Locals

        private string _id;
        private string _availability;
        private string _averageRating;
        private string _title;
        private string _synopsisLink;
        private string _episodesLink;
        private string _castLink;
        private string _genresLink;
        private string _coverId;
        private string _backdropId;
        private string _Synopsis;
        private string _similarLink;
        private string _discLink;
        private string _seasonLink;
        private string _theMovieDbKey = "";
        private string _titleRef;
        private string _shortTitle;
        private string _altTitle;
        private int _releaseYear;
        private int _runTime;
        private bool _isSeries = false;
        private bool _isEpisode = false;
        private bool _isInstant = false;
        private bool _isDvd = false;
        private bool _isBluRay = false;
        private DateTime _updated;
        private List<string> _genres = new List<string>();
        private List<string> _ratings = new List<string>();
        private List<string> _boxArt = new List<string>();
        private List<Formats> _titleFormats = new List<Formats>();
        private ImageProcessor _image = new ImageProcessor();
        private string _theTVDbKey = "";
        private string _theTVDbId = "";

        #endregion

        #region Public

        public string ID
        {
            get { return _id; }
            set { _id = value; }
        }
        public string AverageRating
        {
            get { return _averageRating; }
            set { _averageRating = value; }
        }
        public string Availability
        {
            get { return _availability; }
            set { _availability = value; }

        }
        public string Title
        {
            get { return _title; }
            set { _title = value; }
        }
        public string ShortTitle
        {
            get { return _shortTitle; }
            set { _shortTitle = value; }
        }
        public string AltTitle
        {
            get { return _altTitle; }
            set { _altTitle = value; }
        }
        public DateTime Updated
        {
            get { return _updated; }
            set { _updated = value; }
        }
        public int ReleaseYear
        {
            get { return _releaseYear; }
            set { _releaseYear = value; }
        }
        public int RunTime
        {
            get { return _runTime / 60; }
            set { _runTime = value; }
        }
        public List<string> Genres
        {
            get { return _genres; }
            set { _genres = value; }
        }
        public List<string> Ratings
        {
            get { return _ratings; }
            set { _ratings = value; }
        }
        public bool IsSeries
        {
            get { return _isSeries; }
            set { _isSeries = value; }
        }
        public bool IsEpisode
        {
            get { return _isEpisode; }
            set { _isEpisode = value; }
        }
        public bool IsInstant
        {
            get { return _isInstant; }
            set { _isInstant = value; }
        }
        public bool IsDvd
        {
            get { return _isDvd; }
            set { _isDvd = value; }
        }
        public bool IsBluRay
        {
            get { return _isBluRay; }
            set { _isBluRay = value; }
        }
        public string TitleRef
        {
            get { return _titleRef; }
            set { _titleRef = value; }
        }
        public List<Formats> TitleFormats
        {
            get { return _titleFormats; }
            set { _titleFormats = value; }
        }
        public string SimilarLink
        {
            get { return _similarLink; }
            set { _similarLink = value; }
        }
        public string DiscLink
        {
            get { return _discLink; }
            set { _discLink = value; }
        }
        public string SeasonsLink
        {
            get { return _seasonLink; }
            set { _seasonLink = value; }
        }
        public List<string> BoxArt
        {
            get { return _boxArt; }
            set { _boxArt = value; }
        }
        public string SynopsisLink
        {
            get { return _synopsisLink; }
            set { _synopsisLink = value; }
        }
        public string EpisodesLink
        {
            get { return _episodesLink; }
            set { _episodesLink = value; }
        }
        public string CastLink
        {
            get { return _castLink; }
            set { _castLink = value; }
        }
        public string Synopsis
        {
            get { return _Synopsis; }
            set { _Synopsis = value; }
        }
        public string GenresLink
        {
            get { return _genresLink; }
            set { _genresLink = value; }
        }
        public string CoverId
        {
            get { return _coverId; }
            set { _coverId = value; }
        }
        public string BackdropId
        {
            get { return _backdropId; }
            set { _backdropId = value; }
        }
        public string TheTVDbId
        {
            get { return _theTVDbId; }
        }
        #endregion

        #region Get Images

        /// <summary>
        /// Get the Background Image
        /// </summary>
        public void GetBackgroundImage()
        {
            int tries = 0;
            string title = Title;
            string thisImageURL = "";

            //--------------------------------------------------------------------------------
            // Lets try 3 times to get a good image.
            // Pass 1 is the title
            // Pass 2 removes the ':'
            // Pass 3 removes the special characters (quotes, etc...)
            //--------------------------------------------------------------------------------
            while (tries < 3)
            {
                if (title.StartsWith("0"))
                    title = title.Remove(0, title.IndexOf("-") + 1).Trim();

                if (tries == 1)
                {
                    if (title.Contains(":"))
                        title = title.Substring(0, title.IndexOf(":"));
                }
                if (tries == 2)
                    title = Regex.Replace(title, @"\d", "");

                try
                {
                    if (_isSeries)
                    {

                        XDocument theTVDBCallSeries = XDocument.Load("http://thetvdb.com/api/GetSeries.php?seriesname=" + title);

                        //--------------------------------------------------------------------------------
                        // Now lets get potential matches from thetvdb.com
                        //--------------------------------------------------------------------------------
                        foreach (XElement xe in theTVDBCallSeries.Descendants("Series"))
                        {
                            try
                            {
                                if (xe.Element("SeriesName").Value == title || _releaseYear - DateTime.Parse(xe.Element("FirstAired").Value).Year < 10)
                                {
                                    XDocument theTVdbSeriesInfo = XDocument.Load("http://thetvdb.com/api/" + _theTVDbKey + "/series/" + xe.Element("id").Value + "/");

                                    thisImageURL = "http://thetvdb.com/banners/" + theTVdbSeriesInfo.Element("Data").Element("Series").Element("fanart").Value;
                                    _theTVDbId = xe.Element("id").Value;
                                    tries = 5;
                                    break;
                                }
                            }
                            catch { }

                        }
                    }
                    else
                    {
                        //--------------------------------------------------------------------------------
                        // Get the potential images from TheMovieDb.org
                        //--------------------------------------------------------------------------------
                        XDocument xdoc = XDocument.Load("http://api.themoviedb.org/2.1/Movie.search/en/xml/" + _theMovieDbKey + "/" + title + "+" + _releaseYear);

                        if (xdoc.Element("OpenSearchDescription").Element("movies").Value != "Nothing found.")
                        {
                            IEnumerable<XElement> address = from el in xdoc.Element("OpenSearchDescription").Element("movies").Element("movie").Element("images").Elements("image")
                                                            where (string)el.Attribute("type") == "backdrop" && (string)el.Attribute("size") == "poster"
                                                            select el;

                            foreach (XElement el in address)
                            {
                                thisImageURL = el.Attribute("url").Value;
                                tries = 5;
                                break;
                            }
                        }
                        else if(_releaseYear == 0)
                        {
                            xdoc = XDocument.Load("http://api.themoviedb.org/2.1/Movie.search/en/xml/" + _theMovieDbKey + "/" + title);

                            //--------------------------------------------------------------------------------
                            // Lets check to see if we have any good images
                            //--------------------------------------------------------------------------------
                            if (xdoc.Element("OpenSearchDescription").Element("movies").Value != "Nothing found.")
                            {
                                IEnumerable<XElement> address = from el in xdoc.Element("OpenSearchDescription").Element("movies").Element("movie").Element("images").Elements("image")
                                                                where (string)el.Attribute("type") == "backdrop" && (string)el.Attribute("size") == "poster"
                                                                select el;

                                foreach (XElement el in address)
                                {
                                    thisImageURL = el.Attribute("url").Value;
                                    tries = 5;
                                    break;
                                }
                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                    Log.Error("My NetFlix - QueueItem:GetBackgroundImage: Error - " + ex.Message);
                }

                tries++;
            }

            //--------------------------------------------------------------------------------
            // Lets call the GetBanner method in the imageprocessor class to get the image.
            //--------------------------------------------------------------------------------
            _image.asyncGetBanner(thisImageURL, _coverId);
        }

        /// <summary>
        /// Get the cover image for the item
        /// </summary>
        public void GetCoverImage(string boxArtUrl)
        {
            //--------------------------------------------------------------------------------
            // Get the image from the GetCover method...
            //--------------------------------------------------------------------------------
            _image.asyncGetCover(boxArtUrl, _coverId);
        }

        #endregion

    }
}
